package cn.edu.bupt.spring.transaction.demo.controller;

import cn.edu.bupt.spring.transaction.demo.entity.Account;
import cn.edu.bupt.spring.transaction.demo.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

@RestController
public class AccountController {
    @Resource
    private AccountMapper accountMapper;

    @GetMapping(path = "/", produces = "application/json")
    public List<Account> listAll() {
        List<Account> accounts = accountMapper.selectList(null);
        return accounts;
    }

    @GetMapping(path = "/trans", produces = "application/json")
    @Transactional(isolation=Isolation.READ_UNCOMMITTED)
    public String trans(@RequestParam("amount") Long amount) {
        //查询到AAA的账号然后扣除amount
        Account accountSrc = accountMapper.selectById(1);
        System.out.println("AAA balance:"+accountSrc.getBalance());
        accountSrc.setBalance(accountSrc.getBalance()-amount);
        System.out.println("AAA before update:"+accountSrc.getBalance());
        accountMapper.updateById(accountSrc);
        System.out.println("AAA after update:"+accountSrc.getBalance());
        if(amount == 100){   //当转账金额为100时，人为制造异常
           int error = 100/0;
        }
        //查询到BBB的账号然后增加amount
        Account accountDst = accountMapper.selectById(2);
        System.out.println("BBB balance:"+accountDst.getBalance());
        accountDst.setBalance(accountDst.getBalance()+amount);
        accountMapper.updateById(accountDst);
        System.out.println("BBB after update:"+accountDst.getBalance());
        return "trans finished";
    }
}
